<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>jdk8新特性--Stream | Celts</title><meta name="author" content="PaulGeorge"><meta name="copyright" content="PaulGeorge"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="每天一篇面试小知识  jdk1.8新特性知识点： Lambda 表达式、函数式接口、方法引用和构造器调用、Stream API、接口中的默认方法和静态方法、新时间日期 API 本篇着重介绍一下 stream 流   写在前面 什么是 stream 流？ Java8 中，Collection 新增了两个流方法，分别是 Stream() 和 parallelStream() Java8 中添加了一个">
<meta property="og:type" content="article">
<meta property="og:title" content="jdk8新特性--Stream">
<meta property="og:url" content="https://curry3035.gitee.io/posts/9553/index.html">
<meta property="og:site_name" content="Celts">
<meta property="og:description" content="每天一篇面试小知识  jdk1.8新特性知识点： Lambda 表达式、函数式接口、方法引用和构造器调用、Stream API、接口中的默认方法和静态方法、新时间日期 API 本篇着重介绍一下 stream 流   写在前面 什么是 stream 流？ Java8 中，Collection 新增了两个流方法，分别是 Stream() 和 parallelStream() Java8 中添加了一个">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://curry3035.gitee.io/img/avatar.jpg">
<meta property="article:published_time" content="2021-09-11T14:58:58.000Z">
<meta property="article:modified_time" content="2022-05-26T18:19:37.506Z">
<meta property="article:author" content="PaulGeorge">
<meta property="article:tag" content="进阶">
<meta property="article:tag" content="stream">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://curry3035.gitee.io/img/avatar.jpg"><link rel="shortcut icon" href="/img/ic.ico"><link rel="canonical" href="https://curry3035.gitee.io/posts/9553/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":false,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: PaulGeorge","link":"链接: ","source":"来源: Celts","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'jdk8新特性--Stream',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-27 02:19:37'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/css/background.css"><link rel="stylesheet" href="/css/my.css"><meta name="generator" content="Hexo 5.4.2"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Celts"><span class="site-name">Celts</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-archive"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/photos/"><i class="fa-fw fa fa-camera-retro"></i><span> 图库</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">jdk8新特性--Stream</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-09-11T14:58:58.000Z" title="发表于 2021-09-11 22:58:58">2021-09-11</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-26T18:19:37.506Z" title="更新于 2022-05-27 02:19:37">2022-05-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/jdk8%E6%96%B0%E7%89%B9%E6%80%A7/">jdk8新特性</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>22分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="jdk8新特性--Stream"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p>每天一篇面试小知识</p>
</blockquote>
<p>jdk1.8新特性知识点：</p>
<p><strong>Lambda 表达式、函数式接口、方法引用和构造器调用、Stream API、接口中的默认方法和静态方法、新时间日期 API</strong></p>
<p><strong>本篇着重介绍一下 stream 流</strong></p>
<hr>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-18_22-29-30.png"></p>
<p>写在前面</p>
<p><font color=#008000>什么是 stream 流？</font></p>
<p>Java8 中，Collection 新增了两个流方法，分别是 Stream() 和 parallelStream()</p>
<p>Java8 中添加了一个新的接口类 Stream，相当于高级版的 Iterator，它可以通过 Lambda 表达式对集合进行大批量数据操作，或 者各种非常便利、高效的聚合数据操作。</p>
<p>Stream 将要处理的元素集合看作一种流，在流的过程中，借助 Stream API 对流中的元素进行操作，比如：筛选、排序、聚合等。</p>
<p><font color=#008000>jdk8 为什么要引入 stream 流？</font></p>
<p>在 Java8 之前，我们通常是通过 for 循环或者 Iterator 迭代来重新排序合并数据，又或者通过重新定义 Collections.sorts 的 Comparator 方法来实现，这两种方式对于大数据量系统来说，效率并不是很理想。</p>
<p><font color=#6AAFE6>流不存储数据</font></p>
<span id="more"></span>



<h3 id="stream-概述"><a href="#stream-概述" class="headerlink" title="stream 概述"></a>stream 概述</h3><p>Stream可以由数组或集合创建，对流的操作分为两种：</p>
<ol>
<li>中间操作，每次返回一个新的流，可以有多个。</li>
<li>终端操作，每个流只能进行一次终端操作，终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。</li>
</ol>
<p>另外，Stream有几个特性：</p>
<ol>
<li>stream 不存储数据，而是按照特定的规则对数据进行计算，一般会输出结果。</li>
<li>stream 不会改变数据源，通常情况下会产生一个新的集合或一个值。</li>
<li>stream 具有延迟执行特性，只有调用终端操作时，中间操作才会执行。</li>
</ol>
<p>stream 是元素的集合，这点让 stream 看起来用些类似 Iterator</p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_00-46-42.png"></p>
<br/>

<h3 id="stream-的创建"><a href="#stream-的创建" class="headerlink" title="stream 的创建"></a>stream 的创建</h3><h4 id="通过集合数组创建"><a href="#通过集合数组创建" class="headerlink" title="通过集合数组创建"></a>通过集合数组创建</h4><ol>
<li><p>通过 java.util.Collection.stream() 方法用集合创建流</p>
<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamCreateTest();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamCreateTest</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;a&quot;</span>, <span class="string">&quot;b&quot;</span>, <span class="string">&quot;c&quot;</span>);</span><br><span class="line">        <span class="comment">// 创建一个顺序流</span></span><br><span class="line">        Stream&lt;String&gt; stream = list.stream();</span><br><span class="line">        <span class="comment">// 创建一个并行流</span></span><br><span class="line">        Stream&lt;String&gt; parallelStream = list.parallelStream();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>使用 java.util.Arrays.stream(T[] array) 方法用数组创建流</p>
<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamCreateTest2();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamCreateTest2</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">int</span>[] array = &#123;<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">8</span>&#125;;</span><br><span class="line">        <span class="type">IntStream</span> <span class="variable">stream</span> <span class="operator">=</span> Arrays.stream(array);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>使用 Stream 的静态方法：of()、iterate()、generate()</p>
<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamCreateTest3();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamCreateTest3</span><span class="params">()</span> &#123;</span><br><span class="line">        Stream&lt;Integer&gt; stream = Stream.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>);</span><br><span class="line">        stream.forEach(System.out::println);</span><br><span class="line"></span><br><span class="line">        Stream&lt;Integer&gt; stream2 = Stream.iterate(<span class="number">0</span>, (x) -&gt; x + <span class="number">3</span>).limit(<span class="number">4</span>);</span><br><span class="line">        stream2.forEach(System.out::println);</span><br><span class="line">        </span><br><span class="line">        Stream&lt;Double&gt; stream3 = Stream.generate(Math::random).limit(<span class="number">3</span>);</span><br><span class="line">        stream3.forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ol>
<br/>


<h4 id="stream-和-parallelStream"><a href="#stream-和-parallelStream" class="headerlink" title="stream 和 parallelStream"></a>stream 和 parallelStream</h4><p><font color=#008000>stream</font> 是顺序流，由主线程按顺序对流执行操作</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-18_23-56-01.png" style="zoom:70%;" />

<p><font color=#008000>parallelStream</font> 并行流就是一个把内容分成多个数据块，并用不不同的线程分别处理每个数据块的流。最后合并每个数据块的计算结果</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-18_23-56-15.png" style="zoom:70%;" />

<p>如果流中的数据量足够大，并行流可以加快处速度。</p>
<p>除了直接创建并行流，还可以通过<code>parallel()</code>把顺序流转换成并行流</p>
<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;parallelSum = &quot;</span> + parallelSum(<span class="number">2</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="type">long</span> <span class="title function_">parallelSum</span><span class="params">(<span class="type">long</span> n)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> Stream.iterate(<span class="number">1L</span>, i -&gt; i + <span class="number">1</span>).limit(n).parallel().reduce(<span class="number">0L</span>, Long::sum);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br/>



<h3 id="stream-的使用"><a href="#stream-的使用" class="headerlink" title="stream 的使用"></a>stream 的使用</h3><p>在使用 stream 之前，先看一下：<code>Optional</code></p>
<p><code>Optional</code>类是一个可以为<code>null</code>的容器对象。如果值存在则<code>isPresent()</code>方法会返回<code>true</code>，调用<code>get()</code>方法会返回该对象。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">+--------------------+        +--------+     +--------+     +-----+     +---------+</span><br><span class="line">| stream of elements + -----&gt; | filter + --&gt; | sorted + --&gt; | map + --&gt; | collect |</span><br><span class="line">+--------------------+        +--------+     +--------+     +-----+     +---------+</span><br></pre></td></tr></table></figure>



<p><strong>stream（图示）</strong></p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-18_22-23-04.png"></p>
<hr>
<p><strong>stream–collect（图示）</strong></p>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-18_22-23-39.png"></p>
<hr>
<h4 id="遍历-匹配（foreach-find-match）"><a href="#遍历-匹配（foreach-find-match）" class="headerlink" title="遍历/匹配（foreach/find/match）"></a>遍历/匹配（foreach/find/match）</h4><p><code>Stream</code>也是支持类似集合的遍历和匹配元素的，只是<code>Stream</code>中的元素是以<code>Optional</code>类型存在的。</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_01-39-44.png" style="zoom:80%;" />

<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">7</span>, <span class="number">6</span>, <span class="number">9</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">2</span>, <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 遍历输出符合条件的元素</span></span><br><span class="line">        list.stream().filter(x -&gt; x &gt; <span class="number">6</span>).forEach(System.out::print);</span><br><span class="line">        System.out.println();</span><br><span class="line">        <span class="comment">// 匹配第一个</span></span><br><span class="line">        Optional&lt;Integer&gt; findFirst = list.stream().filter(x -&gt; x &gt; <span class="number">6</span>).findFirst();</span><br><span class="line">        <span class="comment">// 匹配任意（适用于并行流）</span></span><br><span class="line">        Optional&lt;Integer&gt; findAny = list.parallelStream().filter(x -&gt; x &gt; <span class="number">6</span>).findAny();</span><br><span class="line">        <span class="comment">// 是否包含符合特定条件的元素</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">anyMatch</span> <span class="operator">=</span> list.stream().anyMatch(x -&gt; x &lt; <span class="number">6</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;匹配第一个值：&quot;</span> + findFirst.get());</span><br><span class="line">        System.out.println(<span class="string">&quot;匹配任意一个值：&quot;</span> + findAny.get());</span><br><span class="line">        System.out.println(<span class="string">&quot;是否存在大于6的值：&quot;</span> + anyMatch);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="筛选（filter）"><a href="#筛选（filter）" class="headerlink" title="筛选（filter）"></a>筛选（filter）</h4><p>筛选，是按照一定的规则校验流中的元素，将符合条件的元素提取到新的流中的操作。</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_01-40-26.png" style="zoom:80%;" />

<p>举个荔枝：</p>
<p>筛选出<code>Integer</code>集合中大于7的元素，并打印出来</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation2();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation2</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">6</span>, <span class="number">7</span>, <span class="number">3</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">9</span>);</span><br><span class="line">        Stream&lt;Integer&gt; stream = list.stream();</span><br><span class="line">        stream.filter(x -&gt; x &gt; <span class="number">7</span>).forEach(System.out::println);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="聚合（max-min-count"><a href="#聚合（max-min-count" class="headerlink" title="聚合（max/min/count)"></a>聚合（max/min/count)</h4><p><code>max</code>、<code>min</code>、<code>count</code>这些字眼在 mysql 中我们常用它们进行数据统计。</p>
<p>java stream 中也引入了这些概念和用法，极大地方便了我们对集合、数组的数据统计工作。</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_01-46-58.png" style="zoom:80%;" />

<p>举个荔枝：</p>
<p>获取<code>String</code>集合中最长的元素</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation3();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation3</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;adnm&quot;</span>, <span class="string">&quot;admmt&quot;</span>, <span class="string">&quot;pot&quot;</span>, <span class="string">&quot;xbangd&quot;</span>, <span class="string">&quot;weoujgsd&quot;</span>);</span><br><span class="line"></span><br><span class="line">        Optional&lt;String&gt; max = list.stream().max(Comparator.comparing(String::length));</span><br><span class="line">        System.out.println(<span class="string">&quot;最长的字符串：&quot;</span> + max.get());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>再举个荔枝：</p>
<p>获取Integer集合中的最大值</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation4();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation4</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">7</span>, <span class="number">6</span>, <span class="number">9</span>, <span class="number">4</span>, <span class="number">11</span>, <span class="number">6</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 自然排序</span></span><br><span class="line">        Optional&lt;Integer&gt; max = list.stream().max(Integer::compareTo);</span><br><span class="line">        <span class="comment">// 自定义排序</span></span><br><span class="line">        Optional&lt;Integer&gt; max2 = list.stream().max((o1, o2) -&gt; o1.compareTo(o2));</span><br><span class="line">        System.out.println(<span class="string">&quot;自然排序的最大值：&quot;</span> + max.get());</span><br><span class="line">        System.out.println(<span class="string">&quot;自定义排序的最大值：&quot;</span> + max2.get());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="映射（map-flatMap）"><a href="#映射（map-flatMap）" class="headerlink" title="映射（map / flatMap）"></a>映射（map / flatMap）</h4><p>映射，可以将一个流的元素按照一定的映射规则映射到另一个流中</p>
<p>分为<code>map</code>和<code>flatMap</code>：</p>
<ul>
<li><code>map</code>：接收一个函数作为参数，该函数会被应用到每个元素上，并将其映射成一个新的元素。</li>
</ul>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_02-29-38.png" style="zoom:80%;" />

<ul>
<li><code>flatMap</code>：接收一个函数作为参数，将流中的每个值都换成另一个流，然后把所有流连接成一个流。</li>
</ul>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_02-30-15.png" style="zoom:80%;" />

<p>举个荔枝：</p>
<p>英文字符串数组的元素全部改为大写、整数数组每个元素+3</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest3</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation</span><span class="params">()</span> &#123;</span><br><span class="line">        String[] strArr = &#123; <span class="string">&quot;abcd&quot;</span>, <span class="string">&quot;bcdd&quot;</span>, <span class="string">&quot;defde&quot;</span>, <span class="string">&quot;fTr&quot;</span> &#125;;</span><br><span class="line">        List&lt;String&gt; strList = Arrays.stream(strArr).map(String::toUpperCase).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">        List&lt;Integer&gt; intList = Arrays.asList(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">11</span>);</span><br><span class="line">        List&lt;Integer&gt; intListNew = intList.stream().map(x -&gt; x + <span class="number">3</span>).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;每个元素大写：&quot;</span> + strList);</span><br><span class="line">        System.out.println(<span class="string">&quot;每个元素+3：&quot;</span> + intListNew);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>再举个荔枝：</p>
<p>将两个字符数组合并成一个新的字符数组</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest3</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation2();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation2</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;m,k,l,a&quot;</span>, <span class="string">&quot;1,3,5,7&quot;</span>);</span><br><span class="line">        List&lt;String&gt; listNew = list.stream().flatMap(s -&gt; &#123;</span><br><span class="line">            <span class="comment">// 将每个元素转换成一个stream</span></span><br><span class="line">            String[] split = s.split(<span class="string">&quot;,&quot;</span>);</span><br><span class="line">            Stream&lt;String&gt; s2 = Arrays.stream(split);</span><br><span class="line">            <span class="keyword">return</span> s2;</span><br><span class="line">        &#125;).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;处理前的集合：&quot;</span> + list);</span><br><span class="line">        System.out.println(<span class="string">&quot;处理后的集合：&quot;</span> + listNew);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="归约（reduce）"><a href="#归约（reduce）" class="headerlink" title="归约（reduce）"></a>归约（reduce）</h4><p>归约，也称缩减，顾名思义，是把一个流缩减成一个值，能实现对集合求和、求乘积和求最值操作</p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_02-52-43.png" style="zoom:80%;" />

<p>举个荔枝：</p>
<p>求<code>Integer</code>集合的元素之和、乘积和最大值</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest3</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation3();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation3</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">1</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">8</span>, <span class="number">11</span>, <span class="number">4</span>);</span><br><span class="line">        <span class="comment">// 求和方式1</span></span><br><span class="line">        Optional&lt;Integer&gt; sum = list.stream().reduce((x, y) -&gt; x + y);</span><br><span class="line">        <span class="comment">// 求和方式2</span></span><br><span class="line">        Optional&lt;Integer&gt; sum2 = list.stream().reduce(Integer::sum);</span><br><span class="line">        <span class="comment">// 求和方式3</span></span><br><span class="line">        <span class="type">Integer</span> <span class="variable">sum3</span> <span class="operator">=</span> list.stream().reduce(<span class="number">0</span>, Integer::sum);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 求乘积</span></span><br><span class="line">        Optional&lt;Integer&gt; product = list.stream().reduce((x, y) -&gt; x * y);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 求最大值方式1</span></span><br><span class="line">        Optional&lt;Integer&gt; max = list.stream().reduce((x, y) -&gt; x &gt; y ? x : y);</span><br><span class="line">        <span class="comment">// 求最大值写法2</span></span><br><span class="line">        <span class="type">Integer</span> <span class="variable">max2</span> <span class="operator">=</span> list.stream().reduce(<span class="number">1</span>, Integer::max);</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;list求和：&quot;</span> + sum.get() + <span class="string">&quot;,&quot;</span> + sum2.get() + <span class="string">&quot;,&quot;</span> + sum3);</span><br><span class="line">        System.out.println(<span class="string">&quot;list求积：&quot;</span> + product.get());</span><br><span class="line">        System.out.println(<span class="string">&quot;list求和：&quot;</span> + max.get() + <span class="string">&quot;,&quot;</span> + max2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="收集（collect）"><a href="#收集（collect）" class="headerlink" title="收集（collect）"></a>收集（collect）</h4><p><code>collect</code>，收集，可以说是内容最繁多、功能最丰富的部分了。从字面上去理解，就是把一个流收集起来，最终可以是收集成一个值也可以收集成一个新的集合</p>
<blockquote>
<p><code>collect</code>主要依赖<code>java.util.stream.Collectors</code>类内置的静态方法</p>
</blockquote>
<h5 id="归集（toList-toSet-toMap）"><a href="#归集（toList-toSet-toMap）" class="headerlink" title="归集（toList/toSet/toMap）"></a>归集（toList/toSet/toMap）</h5><p>因为流不存储数据，那么在流中的数据完成处理后，需要将流中的数据重新归集到新的集合里</p>
<p><code>toList</code>、<code>toSet</code>和<code>toMap</code>：</p>
<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest4</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Integer&gt; list = Arrays.asList(<span class="number">1</span>, <span class="number">6</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">9</span>, <span class="number">6</span>, <span class="number">20</span>);</span><br><span class="line">        List&lt;Integer&gt; listNew = list.stream().filter(x -&gt; x % <span class="number">2</span> == <span class="number">0</span>).collect(Collectors.toList());</span><br><span class="line">        Set&lt;Integer&gt; set = list.stream().filter(x -&gt; x % <span class="number">2</span> == <span class="number">0</span>).collect(Collectors.toSet());</span><br><span class="line"></span><br><span class="line">        List&lt;Person&gt; personList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;Person&gt;();</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Tom&quot;</span>, <span class="number">8900</span>, <span class="number">23</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Jack&quot;</span>, <span class="number">7000</span>, <span class="number">25</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Lily&quot;</span>, <span class="number">7800</span>, <span class="number">21</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Anni&quot;</span>, <span class="number">8200</span>, <span class="number">24</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line"></span><br><span class="line">        Map&lt;?, Person&gt; map = personList.stream().filter(p -&gt; p.getSalary() &gt; <span class="number">8000</span>)</span><br><span class="line">                .collect(Collectors.toMap(Person::getName, p -&gt; p));</span><br><span class="line">        System.out.println(<span class="string">&quot;toList:&quot;</span> + listNew);</span><br><span class="line">        System.out.println(<span class="string">&quot;toSet:&quot;</span> + set);</span><br><span class="line">        System.out.println(<span class="string">&quot;toMap:&quot;</span> + map);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">toList:[<span class="number">6</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">6</span>, <span class="number">20</span>]</span><br><span class="line">toSet:[<span class="number">4</span>, <span class="number">20</span>, <span class="number">6</span>]</span><br><span class="line">toMap:&#123;Tom=Person&#123;name=<span class="string">&#x27;Tom&#x27;</span>, salary=<span class="number">8900</span>, age=<span class="number">23</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;, Anni=Person&#123;name=<span class="string">&#x27;Anni&#x27;</span>, salary=<span class="number">8200</span>, age=<span class="number">24</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;&#125;</span><br></pre></td></tr></table></figure>



<h5 id="统计（count-averaging）"><a href="#统计（count-averaging）" class="headerlink" title="统计（count/averaging）"></a>统计（count/averaging）</h5><p>Collectors提供了一系列用于数据统计的静态方法：</p>
<ul>
<li>计数：count</li>
<li>平均值：averagingInt、averagingLong、averagingDouble</li>
<li>最值：maxBy、minBy</li>
<li>求和：summingInt、summingLong、summingDouble</li>
<li>统计以上所有：summarizingInt、summarizingLong、summarizingDouble</li>
</ul>
<p>举个荔枝：</p>
<p>统计员工人数、平均工资、工资总额、最高工资</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest4</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation2();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation2</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Person&gt; personList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Tom&quot;</span>, <span class="number">8900</span>, <span class="number">23</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Jack&quot;</span>, <span class="number">7000</span>, <span class="number">25</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Lily&quot;</span>, <span class="number">7800</span>, <span class="number">21</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 求总数</span></span><br><span class="line">        <span class="type">Long</span> <span class="variable">count</span> <span class="operator">=</span> personList.stream().collect(Collectors.counting());</span><br><span class="line">        <span class="comment">// 求平均工资</span></span><br><span class="line">        <span class="type">Double</span> <span class="variable">average</span> <span class="operator">=</span> personList.stream().collect(Collectors.averagingDouble(Person::getSalary));</span><br><span class="line">        <span class="comment">// 求最高工资</span></span><br><span class="line">        Optional&lt;Integer&gt; max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));</span><br><span class="line">        <span class="comment">// 求工资之和</span></span><br><span class="line">        <span class="type">Integer</span> <span class="variable">sum</span> <span class="operator">=</span> personList.stream().collect(Collectors.summingInt(Person::getSalary));</span><br><span class="line">        <span class="comment">// 一次性统计所有信息</span></span><br><span class="line">        <span class="type">DoubleSummaryStatistics</span> <span class="variable">collect</span> <span class="operator">=</span> personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;员工总数：&quot;</span> + count);</span><br><span class="line">        System.out.println(<span class="string">&quot;员工平均工资：&quot;</span> + average);</span><br><span class="line">        System.out.println(<span class="string">&quot;员工工资总和：&quot;</span> + sum);</span><br><span class="line">        System.out.println(<span class="string">&quot;员工工资所有统计：&quot;</span> + collect);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">员工总数：<span class="number">3</span></span><br><span class="line">员工平均工资：<span class="number">7900.0</span></span><br><span class="line">员工工资总和：<span class="number">23700</span></span><br><span class="line">员工工资所有统计：DoubleSummaryStatistics&#123;count=<span class="number">3</span>, sum=<span class="number">23700.000000</span>, min=<span class="number">7000.000000</span>, average=<span class="number">7900.000000</span>, max=<span class="number">8900.000000</span>&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h5 id="分组（partitioningBy-groupingBy）"><a href="#分组（partitioningBy-groupingBy）" class="headerlink" title="分组（partitioningBy/groupingBy）"></a>分组（partitioningBy/groupingBy）</h5><ul>
<li>分区：将<code>stream</code>按条件分为两个<code>Map</code>，比如员工按薪资是否高于8000分为两部分。</li>
<li>分组：将集合分为多个Map，比如员工按性别分组。有单级分组和多级分组。</li>
</ul>
<p><img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_03-54-51.png"></p>
<p>举个荔枝：</p>
<p>将员工按薪资是否高于8000分为两部分；将员工按性别和地区分组</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest4</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation3();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation3</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Person&gt; personList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;Person&gt;();</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Tom&quot;</span>, <span class="number">8900</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Jack&quot;</span>, <span class="number">7000</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Lily&quot;</span>, <span class="number">7800</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Anni&quot;</span>, <span class="number">8200</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Owen&quot;</span>, <span class="number">9500</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Alisa&quot;</span>, <span class="number">7900</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 将员工按薪资是否高于8000分组</span></span><br><span class="line">        Map&lt;Boolean, List&lt;Person&gt;&gt; part = personList.stream().collect(Collectors.partitioningBy(x -&gt; x.getSalary() &gt; <span class="number">8000</span>));</span><br><span class="line">        <span class="comment">// 将员工按性别分组</span></span><br><span class="line">        Map&lt;String, List&lt;Person&gt;&gt; group = personList.stream().collect(Collectors.groupingBy(Person::getSex));</span><br><span class="line">        <span class="comment">// 将员工先按性别分组，再按地区分组</span></span><br><span class="line">        Map&lt;String, Map&lt;String, List&lt;Person&gt;&gt;&gt; group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));</span><br><span class="line">        System.out.println(<span class="string">&quot;员工按薪资是否大于8000分组情况：&quot;</span> + part);</span><br><span class="line">        System.out.println(<span class="string">&quot;员工按性别分组情况：&quot;</span> + group);</span><br><span class="line">        System.out.println(<span class="string">&quot;员工按性别、地区：&quot;</span> + group2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">员工按薪资是否大于<span class="number">8000</span>分组情况：&#123;<span class="literal">false</span>=[Person&#123;name=<span class="string">&#x27;Jack&#x27;</span>, salary=<span class="number">7000</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;Washington&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Lily&#x27;</span>, salary=<span class="number">7800</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;Washington&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Alisa&#x27;</span>, salary=<span class="number">7900</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;], <span class="literal">true</span>=[Person&#123;name=<span class="string">&#x27;Tom&#x27;</span>, salary=<span class="number">8900</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Anni&#x27;</span>, salary=<span class="number">8200</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Owen&#x27;</span>, salary=<span class="number">9500</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;]&#125;</span><br><span class="line">员工按性别分组情况：&#123;female=[Person&#123;name=<span class="string">&#x27;Lily&#x27;</span>, salary=<span class="number">7800</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;Washington&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Anni&#x27;</span>, salary=<span class="number">8200</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Alisa&#x27;</span>, salary=<span class="number">7900</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;], male=[Person&#123;name=<span class="string">&#x27;Tom&#x27;</span>, salary=<span class="number">8900</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Jack&#x27;</span>, salary=<span class="number">7000</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;Washington&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Owen&#x27;</span>, salary=<span class="number">9500</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;]&#125;</span><br><span class="line">员工按性别、地区：&#123;female=&#123;New York=[Person&#123;name=<span class="string">&#x27;Anni&#x27;</span>, salary=<span class="number">8200</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Alisa&#x27;</span>, salary=<span class="number">7900</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;], Washington=[Person&#123;name=<span class="string">&#x27;Lily&#x27;</span>, salary=<span class="number">7800</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;female&#x27;</span>, area=<span class="string">&#x27;Washington&#x27;</span>&#125;]&#125;, male=&#123;New York=[Person&#123;name=<span class="string">&#x27;Tom&#x27;</span>, salary=<span class="number">8900</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;, Person&#123;name=<span class="string">&#x27;Owen&#x27;</span>, salary=<span class="number">9500</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;New York&#x27;</span>&#125;], Washington=[Person&#123;name=<span class="string">&#x27;Jack&#x27;</span>, salary=<span class="number">7000</span>, age=<span class="number">0</span>, sex=<span class="string">&#x27;male&#x27;</span>, area=<span class="string">&#x27;Washington&#x27;</span>&#125;]&#125;&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h5 id="接合（joining）"><a href="#接合（joining）" class="headerlink" title="接合（joining）"></a>接合（joining）</h5><p><code>joining</code>可以将stream中的元素用特定的连接符（没有的话，则直接连接）连接成一个字符串</p>
<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest5</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Person&gt; personList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Tom&quot;</span>, <span class="number">8900</span>, <span class="number">23</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Jack&quot;</span>, <span class="number">7000</span>, <span class="number">25</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Lily&quot;</span>, <span class="number">7800</span>, <span class="number">21</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="type">String</span> <span class="variable">names</span> <span class="operator">=</span> personList.stream().map(p -&gt; p.getName()).collect(Collectors.joining(<span class="string">&quot;,&quot;</span>));</span><br><span class="line">        System.out.println(<span class="string">&quot;所有员工的姓名：&quot;</span> + names);</span><br><span class="line">        List&lt;String&gt; list = Arrays.asList(<span class="string">&quot;A&quot;</span>, <span class="string">&quot;B&quot;</span>, <span class="string">&quot;C&quot;</span>);</span><br><span class="line">        <span class="type">String</span> <span class="variable">string</span> <span class="operator">=</span> list.stream().collect(Collectors.joining(<span class="string">&quot;-&quot;</span>));</span><br><span class="line">        System.out.println(<span class="string">&quot;拼接后的字符串：&quot;</span> + string);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">所有员工的姓名：Tom,Jack,Lily</span><br><span class="line">拼接后的字符串：A-B-C</span><br></pre></td></tr></table></figure>

<hr>
<h5 id="归约（reduce）-1"><a href="#归约（reduce）-1" class="headerlink" title="归约（reduce）"></a>归约（reduce）</h5><p><code>Collectors</code>类提供的<code>reducing</code>方法，相比于<code>stream</code>本身的<code>reduce</code>方法，增加了对自定义归约的支持</p>
<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest5</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation2();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation2</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Person&gt; personList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;&gt;();</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Tom&quot;</span>, <span class="number">8900</span>, <span class="number">23</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Jack&quot;</span>, <span class="number">7000</span>, <span class="number">25</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Lily&quot;</span>, <span class="number">7800</span>, <span class="number">21</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 每个员工减去起征点后的薪资之和</span></span><br><span class="line">        <span class="type">Integer</span> <span class="variable">sum</span> <span class="operator">=</span> personList.stream().collect(Collectors.reducing(<span class="number">0</span>, Person::getSalary, (i, j) -&gt; (i + j - <span class="number">5000</span>)));</span><br><span class="line">        System.out.println(<span class="string">&quot;员工扣税薪资总和：&quot;</span> + sum);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// stream的reduce</span></span><br><span class="line">        Optional&lt;Integer&gt; sum2 = personList.stream().map(Person::getSalary).reduce(Integer::sum);</span><br><span class="line">        System.out.println(<span class="string">&quot;员工薪资总和：&quot;</span> + sum2.get());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">员工扣税薪资总和：<span class="number">8700</span></span><br><span class="line">员工薪资总和：<span class="number">23700</span></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="排序（sorted）"><a href="#排序（sorted）" class="headerlink" title="排序（sorted）"></a>排序（sorted）</h4><p>有两种排序：</p>
<ul>
<li>sorted()：自然排序，流中元素需实现 Comparable 接口</li>
<li>sorted (Comparator com)：Comparator 排序器自定义排序</li>
</ul>
<p>举个荔枝：</p>
<p>将员工按工资由高到低（工资一样则按年龄由大到小）排序</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest5</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation3();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation3</span><span class="params">()</span> &#123;</span><br><span class="line">        List&lt;Person&gt; personList = <span class="keyword">new</span> <span class="title class_">ArrayList</span>&lt;Person&gt;();</span><br><span class="line"></span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Sherry&quot;</span>, <span class="number">9000</span>, <span class="number">24</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Tom&quot;</span>, <span class="number">8900</span>, <span class="number">22</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Jack&quot;</span>, <span class="number">9000</span>, <span class="number">25</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;Washington&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Lily&quot;</span>, <span class="number">8800</span>, <span class="number">26</span>, <span class="string">&quot;male&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line">        personList.add(<span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">&quot;Alisa&quot;</span>, <span class="number">9000</span>, <span class="number">26</span>, <span class="string">&quot;female&quot;</span>, <span class="string">&quot;New York&quot;</span>));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 按工资升序排序（自然排序）</span></span><br><span class="line">        List&lt;String&gt; newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)</span><br><span class="line">                .collect(Collectors.toList());</span><br><span class="line">        <span class="comment">// 按工资倒序排序</span></span><br><span class="line">        List&lt;String&gt; newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())</span><br><span class="line">                .map(Person::getName).collect(Collectors.toList());</span><br><span class="line">        <span class="comment">// 先按工资再按年龄升序排序</span></span><br><span class="line">        List&lt;String&gt; newList3 = personList.stream()</span><br><span class="line">                .sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)</span><br><span class="line">                .collect(Collectors.toList());</span><br><span class="line">        <span class="comment">// 先按工资再按年龄自定义排序（降序）</span></span><br><span class="line">        List&lt;String&gt; newList4 = personList.stream().sorted((p1, p2) -&gt; &#123;</span><br><span class="line">            <span class="keyword">if</span> (p1.getSalary() == p2.getSalary()) &#123;</span><br><span class="line">                <span class="keyword">return</span> p2.getAge() - p1.getAge();</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> p2.getSalary() - p1.getSalary();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).map(Person::getName).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;按工资升序排序：&quot;</span> + newList);</span><br><span class="line">        System.out.println(<span class="string">&quot;按工资降序排序：&quot;</span> + newList2);</span><br><span class="line">        System.out.println(<span class="string">&quot;先按工资再按年龄升序排序：&quot;</span> + newList3);</span><br><span class="line">        System.out.println(<span class="string">&quot;先按工资再按年龄自定义降序排序：&quot;</span> + newList4);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">按工资升序排序：[Lily, Tom, Sherry, Jack, Alisa]</span><br><span class="line">按工资降序排序：[Sherry, Jack, Alisa, Tom, Lily]</span><br><span class="line">先按工资再按年龄升序排序：[Lily, Tom, Sherry, Jack, Alisa]</span><br><span class="line">先按工资再按年龄自定义降序排序：[Alisa, Jack, Sherry, Tom, Lily]</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="提取-组合"><a href="#提取-组合" class="headerlink" title="提取/组合"></a>提取/组合</h4><p>流也可以进行合并、去重、限制、跳过等操作</p>
<p><strong>去重</strong></p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_04-39-03.png" style="zoom:80%;" />

<p><strong>限制</strong></p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_04-40-11.png" style="zoom:80%;" />

<p><strong>跳过</strong></p>
<img src="https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@master/img/all/Snipaste_2021-07-19_04-39-31.png" style="zoom:80%;" />



<p>举个荔枝：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">StreamTest5</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        streamOperation4();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">streamOperation4</span><span class="params">()</span> &#123;</span><br><span class="line">        String[] arr1 = &#123; <span class="string">&quot;a&quot;</span>, <span class="string">&quot;b&quot;</span>, <span class="string">&quot;c&quot;</span>, <span class="string">&quot;d&quot;</span> &#125;;</span><br><span class="line">        String[] arr2 = &#123; <span class="string">&quot;d&quot;</span>, <span class="string">&quot;e&quot;</span>, <span class="string">&quot;f&quot;</span>, <span class="string">&quot;g&quot;</span> &#125;;</span><br><span class="line"></span><br><span class="line">        Stream&lt;String&gt; stream1 = Stream.of(arr1);</span><br><span class="line">        Stream&lt;String&gt; stream2 = Stream.of(arr2);</span><br><span class="line">        <span class="comment">// concat:合并两个流 distinct：去重</span></span><br><span class="line">        List&lt;String&gt; newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());</span><br><span class="line">        <span class="comment">// limit：限制从流中获得前n个数据</span></span><br><span class="line">        List&lt;Integer&gt; collect = Stream.iterate(<span class="number">1</span>, x -&gt; x + <span class="number">2</span>).limit(<span class="number">10</span>).collect(Collectors.toList());</span><br><span class="line">        <span class="comment">// skip：跳过前n个数据</span></span><br><span class="line">        List&lt;Integer&gt; collect2 = Stream.iterate(<span class="number">1</span>, x -&gt; x + <span class="number">2</span>).skip(<span class="number">1</span>).limit(<span class="number">5</span>).collect(Collectors.toList());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;流合并：&quot;</span> + newList);</span><br><span class="line">        System.out.println(<span class="string">&quot;limit：&quot;</span> + collect);</span><br><span class="line">        System.out.println(<span class="string">&quot;skip：&quot;</span> + collect2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">按工资升序排序：[Lily, Tom, Sherry, Jack, Alisa]</span><br><span class="line">按工资降序排序：[Sherry, Jack, Alisa, Tom, Lily]</span><br><span class="line">先按工资再按年龄升序排序：[Lily, Tom, Sherry, Jack, Alisa]</span><br><span class="line">先按工资再按年龄自定义降序排序：[Alisa, Jack, Sherry, Tom, Lily]</span><br></pre></td></tr></table></figure>

<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io">PaulGeorge</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://curry3035.gitee.io/posts/9553/">https://curry3035.gitee.io/posts/9553/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://curry3035.gitee.io" target="_blank">Celts</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E8%BF%9B%E9%98%B6/">进阶</a><a class="post-meta__tags" href="/tags/stream/">stream</a></div><div class="post_share"><div class="social-share" data-image="/img/avatar.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/posts/57459/" title="jdk8新特性--Optional"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">jdk8新特性--Optional</div></div></a></div><div class="next-post pull-right"><a href="/posts/32436/" title="学习--Redis事务、锁机制"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">学习--Redis事务、锁机制</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/posts/55119/" title="每日一面--Files工具类"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-01-01</div><div class="title">每日一面--Files工具类</div></div></a></div><div><a href="/posts/34600/" title="面试一下--JUC入门"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-09-10</div><div class="title">面试一下--JUC入门</div></div></a></div><div><a href="/posts/11315/" title="实践一下--Spring Security"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-01</div><div class="title">实践一下--Spring Security</div></div></a></div><div><a href="/posts/40042/" title="每日一面--反射"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-01</div><div class="title">每日一面--反射</div></div></a></div><div><a href="/posts/56511/" title="实践一下--MySQL 优化"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-01-04</div><div class="title">实践一下--MySQL 优化</div></div></a></div><div><a href="/posts/27951/" title="学习--ElasticSearch"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-29</div><div class="title">学习--ElasticSearch</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">PaulGeorge</div><div class="author-info__description">很多事情就像是旅行一样，当你决定要出发的时候，最困难的那部分其实就已经完成了</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">97</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">64</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/PaulGeorge123"><i class="fab fa-github"></i><span>GitHub URL</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/PaulGeorge123" target="_blank" title="Github"><i class="fab fa-github"></i></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#stream-%E6%A6%82%E8%BF%B0"><span class="toc-number">1.</span> <span class="toc-text">stream 概述</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#stream-%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="toc-number">2.</span> <span class="toc-text">stream 的创建</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%80%9A%E8%BF%87%E9%9B%86%E5%90%88%E6%95%B0%E7%BB%84%E5%88%9B%E5%BB%BA"><span class="toc-number">2.1.</span> <span class="toc-text">通过集合数组创建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#stream-%E5%92%8C-parallelStream"><span class="toc-number">2.2.</span> <span class="toc-text">stream 和 parallelStream</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#stream-%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">3.</span> <span class="toc-text">stream 的使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%81%8D%E5%8E%86-%E5%8C%B9%E9%85%8D%EF%BC%88foreach-find-match%EF%BC%89"><span class="toc-number">3.1.</span> <span class="toc-text">遍历&#x2F;匹配（foreach&#x2F;find&#x2F;match）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%AD%9B%E9%80%89%EF%BC%88filter%EF%BC%89"><span class="toc-number">3.2.</span> <span class="toc-text">筛选（filter）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%81%9A%E5%90%88%EF%BC%88max-min-count"><span class="toc-number">3.3.</span> <span class="toc-text">聚合（max&#x2F;min&#x2F;count)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%98%A0%E5%B0%84%EF%BC%88map-flatMap%EF%BC%89"><span class="toc-number">3.4.</span> <span class="toc-text">映射（map &#x2F; flatMap）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BD%92%E7%BA%A6%EF%BC%88reduce%EF%BC%89"><span class="toc-number">3.5.</span> <span class="toc-text">归约（reduce）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%94%B6%E9%9B%86%EF%BC%88collect%EF%BC%89"><span class="toc-number">3.6.</span> <span class="toc-text">收集（collect）</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%BD%92%E9%9B%86%EF%BC%88toList-toSet-toMap%EF%BC%89"><span class="toc-number">3.6.1.</span> <span class="toc-text">归集（toList&#x2F;toSet&#x2F;toMap）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%BB%9F%E8%AE%A1%EF%BC%88count-averaging%EF%BC%89"><span class="toc-number">3.6.2.</span> <span class="toc-text">统计（count&#x2F;averaging）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%88%86%E7%BB%84%EF%BC%88partitioningBy-groupingBy%EF%BC%89"><span class="toc-number">3.6.3.</span> <span class="toc-text">分组（partitioningBy&#x2F;groupingBy）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%8E%A5%E5%90%88%EF%BC%88joining%EF%BC%89"><span class="toc-number">3.6.4.</span> <span class="toc-text">接合（joining）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%BD%92%E7%BA%A6%EF%BC%88reduce%EF%BC%89-1"><span class="toc-number">3.6.5.</span> <span class="toc-text">归约（reduce）</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8E%92%E5%BA%8F%EF%BC%88sorted%EF%BC%89"><span class="toc-number">3.7.</span> <span class="toc-text">排序（sorted）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8F%90%E5%8F%96-%E7%BB%84%E5%90%88"><span class="toc-number">3.8.</span> <span class="toc-text">提取&#x2F;组合</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/47231/" title="POI读取Excel问题">POI读取Excel问题</a><time datetime="2023-04-11T01:00:00.000Z" title="发表于 2023-04-11 09:00:00">2023-04-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/8422/" title="Excel大文件的上传">Excel大文件的上传</a><time datetime="2023-04-10T01:00:00.000Z" title="发表于 2023-04-10 09:00:00">2023-04-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/55119/" title="每日一面--Files工具类">每日一面--Files工具类</a><time datetime="2023-01-01T01:00:00.000Z" title="发表于 2023-01-01 09:00:00">2023-01-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/34600/" title="面试一下--JUC入门">面试一下--JUC入门</a><time datetime="2022-09-10T01:00:00.000Z" title="发表于 2022-09-10 09:00:00">2022-09-10</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/posts/16284/" title="每日一面--字符流和字节流">每日一面--字符流和字节流</a><time datetime="2022-07-01T01:00:00.000Z" title="发表于 2022-07-01 09:00:00">2022-07-01</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gcore.jsdelivr.net/gh/PaulGeorge123/cloudimg@img/mig2023/background05.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By PaulGeorge</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>